#include "threadPool.h"

int getCurDirPath(int cur_dir_id, MYSQL *conn, char *cur_dir_path) {
  char sql_query[256] = {0};
  snprintf(sql_query, sizeof(sql_query),
           "SELECT path FROM fileSystem WHERE id = %d", cur_dir_id);
  if (0 != mysql_query(conn, sql_query)) {  // 查询错误
    fprintf(stderr, "getCurDirPath() query failed: %s\n",
            mysql_error(conn));
    return -1;
  } else {
    MYSQL_RES *result = mysql_store_result(conn);
    if (NULL == result) {  // 未返回结果集 内存分配失败 连接中断
      fprintf(stderr, "getCurDirPath() store result failed: %s\n",
              mysql_error(conn));
      return -1;
    }
    MYSQL_ROW row = mysql_fetch_row(result);
    if (NULL == row) {
      if (0 != mysql_error(conn)) {  // 读取行过程中发生错误
        fprintf(stderr, "getCurDirPath() fetch row failed: %s\n",
                mysql_error(conn));
        return -1;
      }
    }
    snprintf(cur_dir_path, 128 * sizeof(char), "%s", row[0]);
    mysql_free_result(result);
  }
  printf("getCurDirPath() successful: cur_dir_path = %s\n", cur_dir_path);
  return 0;
}

int mkdirFunc(dirStack_t *pwd, const char *dirs, MYSQL *conn,
    const char *username) {
  int cur_dir_id = pwd->top->data;
  char *token, *saveptr;
  char *dirs_dup = strdup(dirs);
  token = strtok_r(dirs_dup, " ", &saveptr);
  while (token != NULL) {
    char sql_query[512] = {0};
    snprintf(sql_query, sizeof(sql_query),
             "SELECT * FROM fileSystem WHERE filename = '%s' AND username = '%s' AND parent_id = %d AND type = 'd' LIMIT 1",
             token, username, cur_dir_id);
    if (false == isQueryResultExist(conn, sql_query)) {  // 无此目录 可以mkdir
      char parent_dir_path[128] = {0};
      getCurDirPath(cur_dir_id, conn, parent_dir_path);
      char token_path[256] = {0};
      if (pwd->top == pwd->bottom) {  // 在根目录mkdir
        snprintf(token_path, sizeof(token_path), "%s%s", parent_dir_path, token);
      } else {  // 在非根目录mkdir
        snprintf(token_path, sizeof(token_path), "%s/%s", parent_dir_path, token);
      }
      memset(sql_query, 0, sizeof(sql_query));
      snprintf(sql_query, sizeof(sql_query),
              "INSERT INTO fileSystem (filename, username, parent_id, type, path) VALUES ('%s', '%s', %d, 'd', '%s')",
              token, username, cur_dir_id, token_path);
      if (0 != mysql_query(conn, sql_query)) {  // 插入错误
        fprintf(stderr, "mkdirFunc() query failed: %s\n",
                mysql_error(conn));
      } else {
        printf("mkdirFunc() insert successful: sql_query = %s\n", sql_query);
      }
    }
    token = strtok_r(NULL, " ", &saveptr);
  }
  free(dirs_dup);
  return 0;
}
